package com.eeepay.eeepay_v2.activity;

import android.content.Intent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.eeepay.eeepay_v2.R;
import com.eeepay.eeepay_v2.model.UserInfo;
import com.eeepay.eeepay_v2.util.BaseGrpcTask;
import com.eeepay.eeepay_v2.util.Constant;
import com.eeepay.eeepay_v2.util.GrpcUtils;
import com.eeepay.eeepay_v2.view.CustomChooseView;
import com.eeepay.v2_library.ui.ABBaseActivity;
import com.eeepay.v2_library.view.TitleBar;

import java.util.concurrent.TimeUnit;

import cn.eeepay.api.grpc.nano.MerchantSuperSearch;
import cn.eeepay.api.grpc.nano.MerchantSuperSearchServiceGrpc;
import cn.eeepay.api.grpc.nano.ProblemApiServiceGrpc;
import cn.eeepay.api.grpc.nano.ProblemProto;
import io.grpc.ManagedChannel;

/**
 * Created by zw on 2016/3/1 0001.
 * 业务产品、  问题类型
 */
public class DeviceTypeActivity extends ABBaseActivity implements View.OnClickListener {

    private final int DEVICE_TYPE = 0;
    private final int PROBLEM_TYPE = 1;
    private TitleBar titleBar;
    private LinearLayout layout_content;
    private RelativeLayout rl_all;
    private ImageView iv_all;

    private boolean isSingle = true;// 是否是单选
    private boolean isAll = false;//是否全选
    private MerchantSuperSearch.AgentBusiness[] posMsgs;
    private StringBuffer posIdStr = new StringBuffer("");

    private ProblemProto.ProblemTypeMsg[] problemTypes;

    private String intentFlag;

    private Intent intent;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_device_type;
    }

    @Override
    protected void initWidget() {
        titleBar = getViewById(R.id.title_bar);
//        titleBar.setShowRight(View.VISIBLE);
        //add by zhuangzeqin 2017年4月24日11:22:13  隐藏右边的确定按钮
        titleBar.setShowRight(View.GONE);
        titleBar.setRightTextView("确定");
        titleBar.setRightTextColor(R.color.unify_grounding_white);

        layout_content = getViewById(R.id.layout_content);
        rl_all = getViewById(R.id.layout_all);
        iv_all = getViewById(R.id.iv_all);

        if(bundle != null){
            isSingle = bundle.getBoolean("isSingle");
            intentFlag = bundle.getString(Constant.INTENT_FLAG);
        }
        if(isSingle){
            rl_all.setVisibility(View.GONE);
        }

        if(Constant.PROBLEM_TYPE.equals(intentFlag)){
            sendHttpRequest(PROBLEM_TYPE);
            titleBar.setTiteTextView("问题类型");
        }else{
            titleBar.setTiteTextView("业务产品");
            sendHttpRequest(DEVICE_TYPE);
        }


    }

    private void initData(){
            if(Constant.PROBLEM_TYPE.equals(intentFlag)){
                for(int i = 0; i < problemTypes.length; i ++){
                    CustomChooseView chooseView = new CustomChooseView(mContext);
                    chooseView.setTypeId(problemTypes[i].problemType);
                    chooseView.setTitle(problemTypes[i].typeName);
                    chooseView.setTag(i);
                    chooseView.setOnClickListener(this);
                    layout_content.addView(chooseView);
                }
            }else{
                for(int i = 0; i < posMsgs.length; i ++){
                    CustomChooseView chooseView = new CustomChooseView(mContext);
                    chooseView.setTitle(posMsgs[i].bpName);
                    chooseView.setTypeId(posMsgs[i].bpId);
                    chooseView.setTag(i);
                    chooseView.setOnClickListener(this);
                    layout_content.addView(chooseView);
                }
            }
    }

    @Override
    protected void eventOnClick() {
        rl_all.setOnClickListener(this);

        titleBar.setRightOnClickListener(new TitleBar.RightBtnOnClickListener() {
            @Override
            public void onRightClick(View view) {
                getSelectTypeForResult();
            }
        });
    }

    /**
     * 获取选中的结果
     */
    private void getSelectTypeForResult() {
        intent = new Intent();
        if(Constant.PROBLEM_TYPE.equals(intentFlag)){
            for (int i = 0; i < layout_content.getChildCount(); i++) {
                CustomChooseView cv = (CustomChooseView) layout_content.getChildAt(i);
                if (cv.getIsSelected()) {
                    intent.putExtra("problem_type", cv.getTypeId());
                    intent.putExtra("type_name", cv.getLeftTitle());
                }
            }
        }else{
            if (isSingle) {
                for (int i = 0; i < layout_content.getChildCount(); i++) {
                    CustomChooseView cv = (CustomChooseView) layout_content.getChildAt(i);
                    if (cv.getIsSelected()) {
                        intent.putExtra("device_type", cv.getLeftTitle());
                        intent.putExtra("hp_id", cv.getTypeId());
                    }
                }
            } else {
                if (isAll) {
                    intent.putExtra("isAll", isAll);
                } else {
                    StringBuffer buffer = new StringBuffer();
                    for (int i = 0; i < layout_content.getChildCount(); i++) {
                        CustomChooseView cv = (CustomChooseView) layout_content.getChildAt(i);
                        if (cv.getIsSelected()) {
                            buffer.append(cv.getLeftTitle() + ",");
                            posIdStr.append(posMsgs[i].bpId + ",");//所选择设备类型的ID
                        }
                    }
                    if (buffer.length() > 1) {
                        intent.putExtra("device_type", buffer.substring(0, buffer.length() - 1));
                    }
                    if (posIdStr.length() > 1) {
                        intent.putExtra("hp_id", posIdStr.substring(0, posIdStr.length() - 1));
                    }
                }
            }
        }

        setResult(RESULT_OK, intent);
        finish();
    }


    @Override
    protected void sendHttpRequest(int taskId) {
        showProgressDialog();
        switch (taskId){
            case DEVICE_TYPE:
                new GrpcTask().execute(Constant.URL.URL, Constant.URL.PORT);
                break;
            case PROBLEM_TYPE:
                GrpcUtils.getInstance().doGrpcTask(Constant.URL.URL, Constant.URL.PORT
                        , taskId, new GrpcUtils.AsyncTaskListener() {
                    @Override
                    public Object doInBack(ManagedChannel channel, int taskId) {
                        ProblemApiServiceGrpc.ProblemApiServiceBlockingStub stub = ProblemApiServiceGrpc
                                .newBlockingStub(channel)
                                .withDeadlineAfter(5, TimeUnit.SECONDS);
                        ProblemProto.ProblemTypeRequest request = new ProblemProto.ProblemTypeRequest();
                        ProblemProto.ProblemResponse response = stub.getProblemType(request);
                        return response;
                    }

                    @Override
                    public void updateUI(Object result, int taskId) {
                        dismissProgressDialog();
                        if(result == null){
                            showToast("请求失败");
                            return;
                        }
                        ProblemProto.ProblemResponse response = (ProblemProto.ProblemResponse) result;
                        problemTypes = response.problemTypeMsg;
                        initData();
                    }
                });

        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.layout_all://全选
                changeState();
                break;
            default:
                if(v.getTag() != null){
                    int index = (int) v.getTag();
                    singleSelect(index);
                }
                getSelectTypeForResult();
                break;
        }
    }

    /**
     * 单选
     * @param index
     */
    private void singleSelect(int index){
        if(isSingle){
            for (int i = 0; i < layout_content.getChildCount(); i++){
                CustomChooseView childView = (CustomChooseView) layout_content.getChildAt(i);
                if(i == index){
                    childView.setIsSelected(true);
                }else{
                    childView.setIsSelected(false);
                }
            }
        }

    }

    /**
     * 选中全部的时候改变其他状态为不选中
     */
    private void changeState(){
        isAll = !isAll;
        if(isAll){
            iv_all.setVisibility(View.VISIBLE);
            for (int i = 0; i < layout_content.getChildCount(); i++){
                CustomChooseView childView = (CustomChooseView) layout_content.getChildAt(i);
                childView.setIsSelected(false);
                childView.setCanChoose(false);
            }
        }else{
            iv_all.setVisibility(View.GONE);
            for (int i = 0; i < layout_content.getChildCount(); i++){
                CustomChooseView childView = (CustomChooseView) layout_content.getChildAt(i);
                childView.setCanChoose(true);
            }
        }

    }

    private class GrpcTask extends BaseGrpcTask<MerchantSuperSearch.AgentBusinessResponse>{

        @Override
        protected MerchantSuperSearch.AgentBusinessResponse doInBack(ManagedChannel channel) {
            MerchantSuperSearchServiceGrpc.MerchantSuperSearchServiceBlockingStub stub
                    = MerchantSuperSearchServiceGrpc.newBlockingStub(channel);

            MerchantSuperSearch.AgentBusinessRequest request = new MerchantSuperSearch.AgentBusinessRequest();
            request.agenNo = UserInfo.getUserInfo2SP().getAgentNo();
            MerchantSuperSearch.AgentBusinessResponse response = stub.getAgentBusiness(request);
            return response;
        }

        @Override
        protected void updateUI(MerchantSuperSearch.AgentBusinessResponse result) {
            dismissProgressDialog();
            if(result == null){
                showToast("查询失败");
                return;
            }
            if("false".equals(result.success)){
                showToast("查询失败" + result.msg);
                return;
            }
            posMsgs = result.agentBusiness;
            initData();
        }
    }
}
